package com.king.pattem.pool;

import java.util.concurrent.atomic.AtomicInteger;

import org.apache.commons.pool.ObjectPool;
import org.apache.commons.pool.PoolableObjectFactory;
import org.apache.commons.pool.impl.GenericObjectPool;

/**
 * @author taomk
 * @version 1.0
 * @since 15-1-17 下午4:39
 */
public class Main {

	private static PoolableObjectFactory factory = new PoolableObjectFactoryDemo();

	private static ObjectPool pool = new GenericObjectPool(factory);

	private static AtomicInteger endCount = new AtomicInteger(0);

	public static class PoolThread extends Thread {
		public void run() {
			Object obj;
			try {
				for (int i = 0; i < 100; i++) {
					System.out.println("== " + i + " ==");
					// 从池中得到对象
					obj = pool.borrowObject();
					// 模拟使用对象
					System.out.println(obj + " is get");
					// 使用完成后，将对象返回池中
					pool.returnObject(obj);
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				endCount.getAndIncrement();
			}
		}
	}

	public static void main(String [] args) {
		new PoolThread().start();
		new PoolThread().start();
		new PoolThread().start();

		try {
			// 等待3个线程全部结束
			while (true) {
				if (endCount.get() == 3) {
					pool.close();
					break;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
